package tools

import (
	"errors"
	"fmt"
	"os"
	"path"
	"runtime"
	"strings"
)

// 获取项目根目录
func GetProjectBaseDir(projectName string) (string, error) {
	var fullPath string
	_, filename, _, ok := runtime.Caller(0)
	if ok {
		fullPath = path.Dir(filename)
	}

	items := strings.Split(fullPath, projectName)
	if len(items) < 2 {
		return "", fmt.Errorf("projectName not exist")
	}

	if len(items) == 2 {
		return path.Join(items[0], projectName), nil
	}

	for i := 0; i < len(items); i++ {
		dir := path.Join(strings.Join(items[:i+1], projectName), projectName)
		if Exists(path.Join(dir, "go.mod")) {
			return dir, nil
		}
	}
	return "", errors.New("go.mod not found. can not get project base dir")
}

func Exists(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}
